package com.woniuxy.shior;

import com.woniuxy.entity.RbacManager;
import com.woniuxy.service.ManagerService;
import com.woniuxy.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    ManagerService managerService;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     *授权！
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return the AuthorizationInfo associated with this principals.
     * @see SimpleAuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String token = principals.getPrimaryPrincipal() + "";
        String username = JWTUtil.getUsername(token);
        SimpleAuthorizationInfo simpleAuthorizationInfo= new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * A {@code null} return value means that no account could be associated with the specified token.
     *
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token =authenticationToken.getCredentials()+"";
        //直接通过redis进行判断
        RbacManager rbacManager = (RbacManager) redisTemplate.opsForValue().get(token);
        if(rbacManager!=null){
            //直接把token封装进去！SimpleAuthorizationInfo
            return new SimpleAuthenticationInfo(token,token,"myRealm");
        }else{
            throw new AuthenticationException("token被篡改，请重新登录！");
        }
    }
}
